import urllib.request

import http.cookiejar
import urllib.parse

# 1.代码自动登录

# 1. 登陆成功 拿到登录之后的 cookie
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
}

login_url = "https://www.yaozh.com/login"

formdata = {
    "username": "xiaomaoera12",
    "pwd": "lina081012",
    "formhash": "1A412CC72E",
    "backurl": "%2F%2Fwww.yaozh.com"
}

# http.cookiejar 也是用来保存cookie的
cookjar = http.cookiejar.CookieJar()

# cookie的处理器
cook_hanlder = urllib.request.HTTPCookieProcessor(cookjar)

# 自定义opener
opener = urllib.request.build_opener(cook_hanlder)

# open请求数据--登录网址
data_str = urllib.parse.urlencode(formdata).encode('utf-8')
print(data_str)

request = urllib.request.Request(login_url, headers=headers, data=data_str)
opener.open(request)

# 2.带着cookie 访问其他页面
final_url = "https://db.yaozh.com/user"

final_request = urllib.request.Request(final_url, headers=headers)
response = opener.open(final_request)

with open('02coojar.html', 'wb') as f:
    f.write(response.read())
